package newcoder_exp.justPractise;

import org.junit.Test;

import linked.ListNode;

public class NC40 {
    public class Solution {
        /**
         * 
         * @param head1 ListNode类 
         * @param head2 ListNode类 
         * @return ListNode类
         */
        
        public ListNode addInList (ListNode head1, ListNode head2) {
            if (head1 == null || head2 == null) {
                return head1 == null ? head2 : head1;
            }
            
            ListNode a = reverse(head1), b = reverse(head2);
            ListNode res = new ListNode(), result = res;
            int sum = 0, flag = 0;
            while (a != null && b != null) {
                sum = a.val + b.val + flag;
                flag = sum / 10;
                sum %= 10;
                res.next = new ListNode();
                res.next.val = sum;
                a = a.next;
                b = b.next;
                res = res.next;
            }
            ListNode c = a == null ? b : a;
            while (c != null) {
                sum = c.val + flag;
                flag = sum / 10;
                sum %= 10;
                res.next = new ListNode();
                res.next.val = sum;
                c = c.next;
                res = res.next;
            }
            if (flag != 0) {
                res.next = new ListNode();
                res.next.val = flag;
            }
            res = result.next;
            res = reverse(res);
            return res;
        }
        
        public ListNode reverse (ListNode head) {
            ListNode pre = null, post = head, temp;
            while (post != null) {
                temp = post.next;
                post.next = pre;
                pre = post;
                post = temp;
            }
            head.next = null;
            return pre;
        }
    }
    
    @Test
    public void test() {
        ListNode a = ListNode.newListNodeFromArray(new int[]{9,3,7,1,9});
        ListNode B = ListNode.newListNodeFromArray(new int[]{6,3,4,7});
        System.out.println(new Solution().addInList(a, B));
    }
}
